package com.icongyou.enterprise.talent_pool.service;

import com.icongyou.enterprise.talent_pool.entity.AssignmentTagEntity;
import com.icongyou.enterprise.talent_pool.entity.TagEntity;
import com.icongyou.enterprise.talent_pool.mapper.AssignmentTagMapper;
import com.icongyou.enterprise.talent_pool.mapper.TagMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Slf4j
@Service
@RequiredArgsConstructor
public class TagProcessingService {

    private final TagMapper tagMapper;
    private final AssignmentTagMapper assignmentTagMapper;
    private final TagRelevanceCalculationService relevanceCalculationService;

    /**
     * 处理大模型生成的标签，包含存在性检查和近似标签处理
     * @param generatedTagName 生成的标签名称
     * @param similarTags 近似标签列表
     * @return 最终使用的标签ID，如果返回null表示该标签被跳过
     */
    @Transactional
    public String processGeneratedTag(String generatedTagName, List<String> similarTags) {

        // 1. 检查标签表中是否已存在完全相同的标签
        TagEntity existingTag = tagMapper.getTagByName(generatedTagName);
        if (existingTag != null) {
            return existingTag.getTagId();
        }

        // 2. 检查是否有近似标签（基于AI返回的similarTags）
        String similarTagId = findSimilarTagId(generatedTagName, similarTags);
        if (similarTagId != null) {
            String newTagId = createTagEntity(generatedTagName);
            // 复制近似标签的所有任务关联关系
            copyAssignmentTagsFromSimilarTag(newTagId, similarTagId);
            return newTagId;
        }

        // 3. 创建全新标签，并计算与所有截止任务的关联度
        String newTagId = createNewTag(generatedTagName);

        // 为全新标签计算与所有截止任务的关联度
        calculateRelevanceForNewTag(newTagId, generatedTagName);

        return newTagId;
    }

    /**
     * 为全新标签计算与所有截止任务的关联度
     */
    private void calculateRelevanceForNewTag(String tagId, String tagName) {
        try {
            relevanceCalculationService.calculateTagForAllAssignments(tagId, tagName);
        } catch (Exception e) {
            // 不抛出异常，避免影响主流程
        }
    }

    /**
     * 创建全新标签
     */
    private String createNewTag(String tagName) {
        return createTagEntity(tagName);
    }

    /**
     * 查找相似标签（AI建议的）
     */
    public String findSimilarTagId(String generatedTagName, List<String> similarTags) {
        if (similarTags == null || similarTags.isEmpty()) {
            return null;
        }

        // 检查每个AI建议的近似标签是否在数据库中存在
        for (String similarTagName : similarTags) {
            TagEntity existingTag = tagMapper.getTagByName(similarTagName.trim());
            if (existingTag != null) {
                return existingTag.getTagId();
            }
        }

        return null;
    }

    /**
     * 复制近似标签的所有任务关联关系
     */
    @Transactional
    public void copyAssignmentTagsFromSimilarTag(String newTagId, String similarTagId) {

        try {
            // 获取近似标签的所有任务关联
            List<AssignmentTagEntity> similarAssignmentTags = assignmentTagMapper.getAssignmentTagsByTagId(similarTagId);

            if (similarAssignmentTags.isEmpty()) {
                return;
            }

            // 创建新的任务关联关系（使用相同的关联度）
            List<AssignmentTagEntity> newAssignmentTags = new ArrayList<>();
            for (AssignmentTagEntity similarAssignmentTag : similarAssignmentTags) {
                AssignmentTagEntity newAssignmentTag = new AssignmentTagEntity();
                newAssignmentTag.setId(UUID.randomUUID().toString());
                newAssignmentTag.setAssignmentId(similarAssignmentTag.getAssignmentId());
                newAssignmentTag.setTagId(newTagId); // 使用新标签的ID
                newAssignmentTag.setRelevance(similarAssignmentTag.getRelevance());
                newAssignmentTag.setAssignmentWeight(similarAssignmentTag.getAssignmentWeight());
                newAssignmentTag.setCalculatedTime(LocalDateTime.now());
                newAssignmentTags.add(newAssignmentTag);
            }

            // 批量保存新的任务关联关系
            assignmentTagMapper.batchInsertAssignmentTags(newAssignmentTags);

        } catch (Exception e) {
            throw new RuntimeException("复制近似标签关联关系失败", e);
        }
    }

    /**
     * 创建标签实体并保存到数据库
     */
    private String createTagEntity(String tagName) {
        try {
            String newTagId = UUID.randomUUID().toString();
            TagEntity newTag = new TagEntity();
            newTag.setTagId(newTagId);
            newTag.setTagName(tagName);
            newTag.setIsActive(1);
            newTag.setCreatedTime(LocalDateTime.now());

            tagMapper.insertTag(newTag);

            return newTagId;
        } catch (Exception e) {
            throw new RuntimeException("新增标签失败: " + tagName, e);
        }
    }
}